package LeetCode.leetcode501;

import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public int[] findMode(TreeNode root) {
        HashMap<Integer,Integer> map = new HashMap<>();
        test(root,map);
        Set<Integer> set = map.keySet();
        Iterator<Integer> iterator = set.iterator();
        ArrayList<Integer> res = new ArrayList<>();
        int max = Integer.MIN_VALUE;
        while (iterator.hasNext()){
            int cur = iterator.next();
            if (map.get(cur) > max) max = map.get(cur);
        }
        iterator = set.iterator();
        while (iterator.hasNext()){
            int cur = iterator.next();
            if (map.get(cur) == max) res.add(cur);
        }
        return res.stream().mapToInt(Integer::intValue).toArray();
    }

    public static void test(TreeNode root, HashMap<Integer, Integer> map) {
        if (root == null) return;
        test(root.left, map);
        map.compute(root.val, (k, v) -> v == null ? 1 : v + 1);
        test(root.right,map);
    }

}